//
//  YWDoDeteAndUpKeepEquTypeTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 2017/4/27.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWDoDeteAndUpKeepEquTypeTableViewController.h"
#import "YWShowPostTroubleInfoTableViewController.h"
#import "YWPostTroubleTableViewController.h"
#import "YWDoDeteAndUpKeepMissionTableViewController.h"

#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "MBProgressHUD.h"
#import "YWConst.h"
#import "YWLoginTool.h"

#import "YWDoEquipmentMissionCell.h"
#import "YWPostTroubleInfoCell.h"

#import "YWMission.h"
#import "YWEquipment.h"
#import "YWEquipmentManager.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWDBTool.h"
#import "YWMissionManager.h"
#import "YWResourceManager.h"
#import "YWNotifyManager.h"
#import "YWEquipmentType.h"
#import "YWEquipmentFieldRecord.h"

@interface YWDoDeteAndUpKeepEquTypeTableViewController ()<YWDoEquipmentMissionCellDelegate,YWPostTroubleVCDelegate,clickCancelThePostTroubleMissionDelegate>

@property (nonatomic, strong) UIView* footView;
@property (nonatomic, strong) UIButton* myTroublesButton;
@property (nonatomic, strong) UIButton* submitButton;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) NSArray* allEquipments;
@property (nonatomic, strong) NSMutableArray* recordEquipmentIds;
//设备报障数组
@property (nonatomic, strong) NSMutableArray *postTroubleRecordArray;
@property (nonatomic, strong) NSMutableArray * saveEquipmentArray;
@property (nonatomic, strong) NSMutableArray * allEquTypeArray;
//扫描进入任务页面时的时间
@property (nonatomic, assign) NSTimeInterval clientScanTime;
//cell的row数组，当设备参数*没填时，让cell边框变红
@property (nonatomic, strong) NSMutableArray * redBorderArray;
@end

@implementation YWDoDeteAndUpKeepEquTypeTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:_maintenanceMission.maintenanceTypeId];
    self.title = typeName;
    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    [self setupTableView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)setupTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    //    self.tableView.rowHeight = 58.0f;
    self.tableView.tableFooterView = self.footView;
    
    [self.tableView setEditing:YES];
    self.tableView.allowsSelectionDuringEditing=YES;
    
    [self.tableView registerClass:[YWDoEquipmentMissionCell class] forCellReuseIdentifier:YWDoEquipmentMissionCellIdentifier];
}
- (NSMutableArray *)recordEquipmentIds{
    if (!_recordEquipmentIds) {
        NSDictionary* recordsDir = [YWDetectAndUpkeepManager detectAndUpkeepRecordsWithMission:_maintenanceMission];
        _recordEquipmentIds = [NSMutableArray array];
        for (NSNumber* locationIdNumber in recordsDir.allKeys) {
            NSArray* records = [recordsDir objectForKey:locationIdNumber];
            if (_maintenanceMission.equipments.count>0) {//_maintenanceMission.type == YWMissionTypeAuto
                [records enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *equipmentId = [dic objectForKey:@"equipmentId"];
                    YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)[dic objectForKey:@"record"];
                    if (equipmentId.length && [record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
                        [_recordEquipmentIds addObject:equipmentId];
                    }
                }];
            }else{
                [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord*  _Nonnull record, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
                        if (record.equipmentId) {
                            [_recordEquipmentIds addObject:record.equipmentId];
                        }
                    }
                }];
            }
        }
    }
    return _recordEquipmentIds;
}

- (void)setMaintenanceMission:(YWMaintenanceMission *)maintenanceMission{
    _maintenanceMission = maintenanceMission;
    if (_qrCodeId) {
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
    
    NSArray *missionEquipments = nil;
    if (_maintenanceMission.equipments.count) {
        missionEquipments = _maintenanceMission.equipments;
    }else{
        missionEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId orLocationId:_locationId equipmentTypeId:_maintenanceMission.equipmentTypeId];
    }
    
    _allEquTypeArray = [NSMutableArray array];
    __block NSInteger lastEquipmentTypeId = 0;
    __block NSMutableArray *array = nil;
    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        [missionEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull missionEqu, NSUInteger idx, BOOL * _Nonnull equStop) {
            if ([missionEqu.equipmentId isEqualToString:equipment.equipmentId] && ![self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                if (_currentEquipment == nil) {
//                    _currentEquipment = equipment;
//                }
                //按照设备类型分组
                NSInteger equipmentTypeId = equipment.equipmentTypeId;
                if (lastEquipmentTypeId==0 || equipmentTypeId !=lastEquipmentTypeId) {
                    lastEquipmentTypeId = equipmentTypeId;
                    array = [NSMutableArray array];
                }
                [array addObject:equipment];
                if (![_allEquTypeArray containsObject:array] && array.count) {
                    [_allEquTypeArray addObject:array];
                }

                if (equipment.equipmentId) {
//                    [self.missionEquipmntIds addObject:equipment.equipmentId];
                    //自动保存要做的设备
                    [self.saveEquipmentArray addObject:equipment];
                }
            }
        }];
        NSArray *runTimeParameterArray = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:maintenanceMission.maintenanceTypeId];
        equipment.runTimeParameterArray = runTimeParameterArray.count?runTimeParameterArray:nil;
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _allEquTypeArray.count>0?_allEquTypeArray.count:1;
    }else{
        return _postTroubleRecordArray.count ?: 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (_allEquTypeArray.count>0) {
            YWDoEquipmentMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDoEquipmentMissionCellIdentifier];
            cell.delegate = self;
            cell.equipmentArray = self.allEquTypeArray[indexPath.row];
            if ([self.redBorderArray containsObject:@(indexPath.row)]) {
                cell.layer.borderWidth = 1.0;
                cell.layer.borderColor = [UIColor customRedColor].CGColor;
            }else{
                cell.layer.borderColor = [UIColor whiteColor].CGColor;
                cell.layer.borderWidth = 0;
            }
            return cell;
        }else{
            static NSString *identifier = @"YWDoDeteAndUpKeepEquTypeTableViewControllerIdentifier";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            cell.textLabel.text = NSLocalizedString(@"none", nil);
            return cell;
        }
    }else{
        YWPostTroubleInfoCell* cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count > 0 ? _postTroubleRecordArray[indexPath.row] : nil;
        cell.reportTrouble = reportTrouble;
        return cell;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWDoEquipmentInspMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString* headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString*)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else{
        return NSLocalizedString(@"postTroubleEquipment", nil);//@"报障设备";
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        return self.postTroubleRecordArray.count ? 58 :44;
    }else{
        return self.allEquTypeArray.count>0?58:44;
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (_allEquTypeArray.count>0) {
            NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
            [equTypeArray enumerateObjectsUsingBlock:^(YWEquipment *     _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
                NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %@", @"equipmentId", equipment.equipmentId];
                NSArray *array = [[self.saveEquipmentArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
                if (array.count>0) {
                    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
                    *stop = YES;
                }else{
                    [tableView deselectRowAtIndexPath:indexPath animated:NO];
                }
            }];
        }
    }
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;//indexPath.section == 0 ? (UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert) : UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 && _allEquTypeArray.count>0 ? YES : NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (_allEquTypeArray.count>0) {
            NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
            [self.saveEquipmentArray addObjectsFromArray:equTypeArray];
        }
    }else{
        YWReportTroubleModel * reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
        if (reportTrouble) {
            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
            showPostTroubleVC.reportTrouble = reportTrouble;
            showPostTroubleVC.delegate = self;
            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
        }
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (_allEquTypeArray.count>0) {
            NSArray * equTypeArray = _allEquTypeArray[indexPath.row];
            [self.saveEquipmentArray removeObjectsInArray:equTypeArray];
        }
    }
}

- (UIView*)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        //      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
        //      提交
        _submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _submitButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _submitButton.layer.masksToBounds = YES;
        _submitButton.layer.cornerRadius = 5.0;
        
        [_submitButton setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _submitButton.backgroundColor = [UIColor customBlueColor];
        [_submitButton addTarget:self action:@selector(clickCommintButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_submitButton];
        
    }
    return _footView;
}

- (NSMutableArray *)saveEquipmentArray{
    if (!_saveEquipmentArray) {
        _saveEquipmentArray = [NSMutableArray array];
    }
    return _saveEquipmentArray;
}

- (NSMutableArray *)redBorderArray{
    if (!_redBorderArray) {
        _redBorderArray = [NSMutableArray array];
    }
    return _redBorderArray;
}

#pragma mark - YWDoEquipmentMissionCellDelegate event
- (void)clickLabelEvent:(UITableViewCell *)cell{
    //代理点击事件
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(YWDoEquipmentMissionCell*)cell];
    YWDoDeteAndUpKeepMissionTableViewController * equDeteAndUpKeepMissionVC = [[YWDoDeteAndUpKeepMissionTableViewController alloc] init];
    equDeteAndUpKeepMissionVC.maintenanceMission = self.maintenanceMission;
    equDeteAndUpKeepMissionVC.allEquipments = self.allEquTypeArray[indexPath.row];
    equDeteAndUpKeepMissionVC.saveEquipmentArray = self.saveEquipmentArray;
    equDeteAndUpKeepMissionVC.qrCodeId = self.qrCodeId;
    equDeteAndUpKeepMissionVC.locationId = self.locationId;
    equDeteAndUpKeepMissionVC.doDeteAndUpKeepEquTypeVC = self;
    [self.navigationController pushViewController:equDeteAndUpKeepMissionVC animated:YES];
    [self.redBorderArray removeAllObjects];
}

#pragma mark - clickCancelThePostTroubleMissionDelegate
- (void)clickCancelTheReportTrouble:(YWReportTroubleModel*)reportTrouble{
    if ([_postTroubleRecordArray containsObject:reportTrouble]) {
        [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
        [_postTroubleRecordArray removeObject:reportTrouble];
        [self.tableView reloadData];
    }
}

#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton*)sender{
    //报障
    NSArray *allEquipmentArray = nil;
    if (_allEquipments) {
        allEquipmentArray = _allEquipments;
    }else if(_qrCodeId) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
    
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];;
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrCodeId;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = self;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}

#pragma mark - YWPostTroubleVCDelegate
- (void)passBackReportTrouble:(YWReportTroubleModel*)reportTrouble{
    //报修记录
    if (!_postTroubleRecordArray) {
        _postTroubleRecordArray = [NSMutableArray array];
    }
    if (reportTrouble) {
        [_postTroubleRecordArray addObject:reportTrouble];
        [self.tableView reloadData];
    }
}

- (void)clickCommintButtonEvent:(UIButton*)sender{
    
    if (_saveEquipmentArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"saveMaintenanceRecordBeforeCommit", nil)];
        return;
    }
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [self.saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger equIdx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:equipment.psText] ) {
            containEmoji = YES;
            *stop = YES;
        }
        [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
            if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
                [self.allEquTypeArray enumerateObjectsUsingBlock:^(NSArray *  _Nonnull array, NSUInteger idx, BOOL * _Nonnull arrayStop) {
                    YWEquipment * equ = array.count?array[0]:nil;
                    if (equ.equipmentTypeId == equipment.equipmentTypeId) {
                        [self.redBorderArray addObject:@(idx)];
                        isRequire = NO;
                        *fieldStop = YES;
                        *stop = YES;
                        *arrayStop = YES;
                    }
                }];
            }
            if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
                reasonable = field.fieldName;
                //*fieldStop = YES;
            }
            if ([YWCommonTool isContainsEmoji:field.fieldValue]){
                containEmoji = YES;
                *stop = YES;
            }
        }];
    }];
    if (!isRequire) {
        [self.tableView reloadData];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToCommit", nil)];
        
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self commitRecord];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self commitRecord];
    }
//    NSString* content = @"";
//    if (_postTroubleRecordArray.count>0) {
//        content = [NSString stringWithFormat:@"提交记录: 有报障,请确定"];
//    }else{
//        content = [NSString stringWithFormat:@"提交记录: 正常,请确定"];
//    }
//    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:content preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.HUD show:YES];
//        [self commitRecord];
//    }]];
//    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)commitRecord{
    NSString *content = [NSString stringWithFormat:NSLocalizedString(kTextConfirmSubmitMission, nil)];
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:content preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        //上传报障
        [self.postTroubleRecordArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTrouble.troubleId maintenanceType:reportTrouble.maintenanceTypeId];
                //                [[YWMissionManager shareManager] startUploadRecords:nil Mission:troubleMission pictures:troublePicureArray];
                [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:troublePicureArray];
            });
        }];
        
        _maintenanceMission.completedQuantity = _maintenanceMission.completedQuantity + _saveEquipmentArray.count;
        _maintenanceMission.finishTime = [[NSDate date] timeIntervalSince1970] * 1000;
        
        if (_maintenanceMission.equipmentQuantity <= _maintenanceMission.completedQuantity) {
            _maintenanceMission.missionStatus = YWMissionStatusFinished;
        }
        
        __block NSArray* equipmentMaintenanceRecords = [self createEquipmentMaintenanceRecords];
        __block NSArray* pictures = [self createPictureWithRecords:equipmentMaintenanceRecords];
        __block NSArray* equipmentFields = [self createEquipmentFieldsRecordsWithRecords:equipmentMaintenanceRecords];
        
        
        BOOL saveMission = [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:_maintenanceMission? @[ _maintenanceMission ] : nil];
        BOOL saveMaintenanceRecord = [YWDetectAndUpkeepManager updateMaintenanceRecords:equipmentMaintenanceRecords maintenanceTypeId:_maintenanceMission.maintenanceTypeId];
        BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFields];
        
        BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
        if (saveMission && saveMaintenanceRecord && savePicturesToDB && saveEquipmetFieldRecord) {
            [self.HUD hide:YES];
            //提交记录
            [[YWDetectAndUpkeepManager alloc] startUploadDetectAndUpkeepRecords:equipmentMaintenanceRecords maintenanceMission:_maintenanceMission pictures:pictures];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[YWNotifyManager shareManager] postMissionFinishedNotifyWithMission:_maintenanceMission];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [self.HUD hide:YES];
            YWLog(@"保存数据库失败");
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitTaskFail, nil)];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSArray*)createPictureWithRecords:(NSArray*)records
{
    NSMutableArray* pictures = [NSMutableArray array];
    [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
        YWEquipment *equipment = _saveEquipmentArray[idx];
        for (int i = 0; i < [equipment.totalImageNameArray count]; i++) {
            YWPicture* picture = [[YWPicture alloc] init];
            picture.pictureId = [YWCommonTool randStringId];
            picture.pictureName = equipment.totalImageNameArray[i];
            picture.isLocalImage = YES;
            picture.uploadStatus = YWPictureUploadStatusNull;
            picture.missionId = _maintenanceMission.missionId;
            picture.maintenanceType = _maintenanceMission.maintenanceTypeId;
            picture.equipmentId = record.equipmentId;
            picture.recordId = record.recordId;
            [pictures addObject:picture];
        }
    }];
    return pictures;
}
- (NSArray*)createEquipmentMaintenanceRecords
{
    NSMutableArray* equipmentMaintenanceRecords = [NSMutableArray array];
    
    [_saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
        YWEquipmentMaintenanceRecord* maintenanceRecord = [[YWEquipmentMaintenanceRecord alloc] init];
        //这里原来有减idx  -idx（改了时间戳的方法后就删掉了）
        maintenanceRecord.recordId = [YWCommonTool negativeTimestampId] ;
        /**任务ID*/
        maintenanceRecord.missionId = _maintenanceMission.missionId;
        NSString *uniqueTag = [YWCommonTool randStringId];
        maintenanceRecord.maintenanceTypeId = _maintenanceMission.maintenanceTypeId;
        maintenanceRecord.uniqueTag = uniqueTag;
        maintenanceRecord.equipmentId = equipment.equipmentId;
        maintenanceRecord.note = [equipment.psText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        maintenanceRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
        maintenanceRecord.clientScanTime = _clientScanTime;
        maintenanceRecord.handlerName = [YWLoginTool loginUser].userName;
        maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusNormal;
        maintenanceRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
        
        NSString *dayMonthString = [YWCommonTool showTime:maintenanceRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
        maintenanceRecord.dayMonthString = dayMonthString;
        //检测保养都是正常完成状态，没有故障状态
        //if (self.postTroubleRecordArray.count>0) {
        //maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusTrouble;
        //}
        
        [equipmentMaintenanceRecords addObject:maintenanceRecord];
    }];
    return equipmentMaintenanceRecords;
}
- (NSArray*)createEquipmentFieldsRecordsWithRecords:(NSArray*)records{
    __block NSMutableArray* fieldsArray = nil;
    __block NSMutableArray* allFieldRecords = [NSMutableArray array];
    [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
        YWEquipment *equipment = _saveEquipmentArray[idx];
        if ([record.equipmentId isEqualToString:equipment.equipmentId]) {
            fieldsArray = [[NSMutableArray alloc]init];
            [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull stop) {
                YWEquipmentFieldRecord *fieldRecord = [[YWEquipmentFieldRecord alloc]init];
                fieldRecord.uniqueTag = record.uniqueTag;
                fieldRecord.fieldId = field.fieldId;
                fieldRecord.fieldName = field.fieldName;
                if (field.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                    fieldRecord.fieldTypeId = YWEquipmentFieldTypeIdDownSelect;
                    fieldRecord.fieldOption = field.fieldOptionValue;
                }else{
                    fieldRecord.fieldValue = field.fieldValue;
                }
                fieldRecord.maintenanceTypeId = _maintenanceMission.maintenanceTypeId;
                [fieldsArray addObject:fieldRecord];
                [allFieldRecords addObject:fieldRecord];
            }];
            record.equipmentFieldRecord = fieldsArray;
        }
    }];
    return allFieldRecords;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
